﻿using System;
using System.Collections.Generic;
using System.Text;
using com.dz.ct.html;
using System.Text.RegularExpressions;
using com.dz.ct.common;
using System.Web;

namespace com.dz.ct.components.SmallSite.www.baidu.com
{
    public class SmallSiteObject
    {

        public string GetChapterContentFromBaiDu(string i_book_chapter_name)
        {
            /// <summary>
            /// 百度首页编码
            /// </summary>
            Encoding t_encoding = Encoding.GetEncoding("gb2312");
            string i_chapter_content_url = string.Format("http://www.baidu.com/s?wd={0}", HttpUtility.UrlEncode(i_book_chapter_name, t_encoding));
            string t_url = string.Empty;
            string t_chapter_name = i_book_chapter_name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1].ToString();

            if (t_chapter_name.IndexOf("章") > -1)
            {
                t_chapter_name = t_chapter_name.Substring(0, t_chapter_name.IndexOf("章") + 1);
            }
            string t_chapter_content = string.Empty;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_content_url, t_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma = Regex.Matches(t_html, "<h3\\s*?class=[\'\"]?t[\'\"]?><a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>(.*?)</a>\\s*?</h3>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma == null || t_ma.Count <= 0)
                        return string.Empty;
                    foreach (Match t_mc in t_ma)
                    {
                        if (t_mc.Groups.Count == 3)
                        {
                            t_url = t_mc.Groups[1].Value.ToString();
                            if (string.IsNullOrEmpty(t_chapter_content))
                            {
                                t_chapter_content = GetContent(t_url, t_chapter_name);
                                if (string.IsNullOrEmpty(t_chapter_content))
                                    continue;
                                else
                                    break;
                            }
                            else
                            {

                                break;
                            }
                        }
                    }

                    t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);
                    t_chapter_content = string.Format("document.write('{0}');", t_chapter_content);
                    return t_chapter_content;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取网站代码失败" + ex.ToString());
            }
            return string.Empty;
        }

        private string GetContent(string i_url, string i_chapter_name)
        {

            Encoding t_encoding = Encoding.Default;
            int t_chapter_name_index = 0;
            string t_chapter_content = string.Empty;
            string t_tem_chapter_content = string.Empty;
            string t_charset = string.Empty;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_url, t_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {
                    t_chapter_name_index = t_html.LastIndexOf(i_chapter_name);
                    //不包含章节名称
                    if (t_chapter_name_index < 0)
                    {
                        Match t_mc_charset = Regex.Match(t_html, "<meta[^<>]*?charsets*=s*[\'\"]*?([^\"\'\\s\\/]*)[\'\"]*?[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        if (t_mc_charset != null)
                        {
                            t_charset = t_mc_charset.Groups[1].Value.ToString();

                            t_encoding = Encoding.GetEncoding(t_charset);

                            t_html = NetSiteCatchManager.ReadUrl(i_url, t_encoding);

                            t_chapter_name_index = t_html.LastIndexOf(i_chapter_name);

                            if (t_chapter_name_index < 0)
                                return string.Empty;
                        }
                    }

                   t_chapter_content= GetChapterContent(t_html);
                }

                return t_chapter_content;

            }
            catch (Exception ex)
            {
                LogHelper.Error("获取页面内容失败" + ex.ToString());
                LogHelper.Info("站点编码:" + t_charset);
                return string.Empty;
            }
        }


        /// <summary>
        /// 获取html章节内容
        /// </summary>
        /// <param name="i_html"></param>
        /// <param name="i_chapter_name"></param>
        /// <returns></returns>
        private string GetChapterContent(string i_html)
        {
            HtmlDocument t_html_doc = HtmlDocument.Create(i_html);
         
            string t_content = string.Empty;
            string t_temp_content = string.Empty;
            foreach (HtmlElement t_ele in t_html_doc.GetElementsByTagName("td"))
            {
                t_temp_content = t_ele.InnerText;
                t_temp_content = Regex.Replace(t_temp_content, "<.*?>.*?</.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                t_temp_content = Regex.Replace(t_temp_content, "[a-zA-Z0-9]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                if (t_temp_content.Length > 800)
                {
                    t_content = t_ele.HTML;
                }

            }
            if (!string.IsNullOrEmpty(t_content))
                return t_content;

            foreach (HtmlElement t_ele in t_html_doc.GetElementsByTagName("div"))
            {
                t_temp_content = t_ele.InnerText;
                t_temp_content = Regex.Replace(t_temp_content, "<.*?>.*?</.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                t_temp_content = Regex.Replace(t_temp_content, "[a-zA-Z0-9,\\/;_()]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                if (t_temp_content.Length > 800)
                {
                    t_content = t_ele.HTML;
                }

            }
           
            return t_content;
        }
    }

    
}
